﻿package  com.hadron.components.slideshow
{
	import com.hadron.events.HadronEvent;
	import flash.display.Bitmap;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import com.caurina.transitions.Tweener;
	import com.caurina.transitions.properties.ColorShortcuts;
	
	/**
	 * ...
	 * @author Hadron
	 */
	public class SlideShow extends MovieClip
	{
		//array of bitmaps loaded
		private var objArr:Array;
		private var index:int = 0;
		private var fadeDuration:Number;
		private var displayTime:Number;
		private var target:Bitmap;
		private var crossOver:Boolean;
		
		private var mainTimer:Timer;
	
		private var bmp:Bitmap;
		
		public function SlideShow(objArr:Array, fadeDuration:Number = 1.5, displayTime:Number = 3, crossOver:Boolean = false) 
		{
			ColorShortcuts.init();
			this.objArr = objArr;
			this.fadeDuration = fadeDuration;
			this.displayTime = displayTime * 1000;
			this.crossOver = crossOver;
			initSlideShow();
		}
		
		private function initSlideShow():void
		{
			for each (var bmp:Bitmap in objArr)
			{
				bmp.alpha = 0;
				bmp.visible = false;
				addChild(bmp);
			}
			target = objArr[index];
			
			//set maintimer
			mainTimer = new Timer(displayTime, 1);
			mainTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onMainTimerComplete);
		}
		
		public function startSlideShow():void
		{
			if (index >= objArr.length)
			{
				index = 0;
			}
			target = objArr[index];
			addChild(objArr[index]);
			fadeIn();
		}
		
		private function fadeIn():void
		{
			Tweener.addTween(target, 
			{ 
				alpha:1,
				time:fadeDuration,
				transition:"easeOutSine",
				onStart:function() 
				{ 
					target.visible = true;
				},
				onComplete:function() 
				{ 
					if (index == 0)
					{
						// take last item in array
						objArr[objArr.length - 1].alpha = 0;
						objArr[objArr.length - 1].visible = true;
						removeChild(objArr[objArr.length - 1]);
					}
					
					if (index > 0)
					{
						objArr[index - 1].alpha = 0;
						objArr[index - 1].visible = false;
						removeChild(objArr[index - 1]);
					}
					
					mainTimer.reset();
					mainTimer.start();
				} 
			});
			
			dispatchEvent(new HadronEvent(HadronEvent.ON_DATA, false, false, index));
		}
		
		private function onMainTimerComplete(e:TimerEvent):void
		{
			//if crossOver true
			if (crossOver)
			{
				index++;
				startSlideShow();
			}
			else
			{
				fadeOut();
			}
		}
		
		private function fadeOut():void
		{
			Tweener.addTween(target,
			{
				alpha:0,
				time:fadeDuration,
				transition:"easeOutSine",
				onComplete:function() 
				{	
					target.visible = false;
					index++;
					startSlideShow();
				}
			} );
		}
	}
}